from flask import (Blueprint, request)
from db import DBSession, Role, Author
from utils import normalizeRes
import datetime

bp = Blueprint('role', __name__, url_prefix='/api/system/role')


# 获取角色列表
@bp.route('/list', methods=['GET'])
def get_roles():
    try:
        session = DBSession()
        roles = session.query(Role).all()
        role_list = []
        for role in roles:
            role_list.append({
                'roleId': role.role_id,
                'isEnable': role.is_enable,
                'isDanger': role.is_danger,
                'name': role.name,
                'updateTime': role.update_time
            })
        return normalizeRes({
            'list': role_list,
            'total': 1
        })
    except Exception as e:
        print("出错" + e)
    finally:
        session.close()


# 创建角色
@bp.route('/create', methods=['POST'])
def create_role():
    try:
        session = DBSession()
        new_role = Role(
            name=request.json['name'],
            is_danger=request.json.get('isDanger', True),
            is_enable=request.json.get('isEnable', True),
            creation_time=datetime.datetime.now()
        )
        authors = session.query(Author).filter(Author.id.in_(request.json.get('auths'))).all()
        new_role.authors = authors
        session.add(new_role)
        session.commit()
        return normalizeRes({
            'new_role': request.json
        })
    except Exception as e:
        print('出错' + e)
    finally:
        session.close()


# 获取角色详情
@bp.route('/detail/<int:roleId>', methods=['GET'])
def get_detail(roleId):
    try:
        session = DBSession()
        role = session.query(Role).filter_by(role_id=roleId).one()
        auths = list(map(lambda author: author.id, role.authors))
        return normalizeRes({
            'roleId': role.role_id,
            'isEnable': role.is_enable,
            'isDanger': role.is_danger,
            'auths': auths,
            'name': role.name
        })
    except Exception as e:
        print(e)
    finally:
        session.close()


# 修改角色
@bp.route('/detail/<int:roleId>', methods=['PUT'])
def modify_detail(roleId):
    try:
        updateRole = request.json
        print('update', updateRole)
        session = DBSession()
        role = session.query(Role).filter_by(role_id=roleId).one()
        role.is_enable = updateRole.get('isEnable', role.is_enable)
        role.is_danger = updateRole.get('isDanger', role.is_danger)
        role.name = updateRole.get('name', role.name)
        if updateRole.get('auths'):
            role.authors = session.query(Author).filter(Author.id.in_(updateRole.get('auths'))).all()
        result = normalizeRes({
            'isEnable': role.is_enable,
            'isDanger': role.is_danger,
            'name': role.name
        })
        session.commit()
        session.close()
        return result
    except Exception as e:
        print('修改角色出错' + e)
    finally:
        session.close()

